package com.lg.online_shop.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.online_shop.entity.Favorite;
import com.lg.online_shop.entity.Good;
import com.lg.online_shop.mapper.FavoriteMapper;
import com.lg.online_shop.mapper.GoodMapper;
import com.lg.online_shop.utils.Result;
import com.lg.online_shop.vo.FavoriteList;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/favorite")
public class FavoriteController {

    @Resource
    FavoriteMapper favoriteMapper;

    @Resource
    GoodMapper goodMapper;


//    获取收藏夹
    @GetMapping("/getFavorite")
    public Result getFavorite(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        // 创建分页对象
        Page<Favorite> favoritePage = new Page<>(page, pageSize);

        // 查询带分页的收藏列表
        Page<Favorite> favoriteListPage = favoriteMapper.selectFavoriteByUserId(favoritePage, userId);
        List<Favorite> favoriteList = favoriteListPage.getRecords();

        FavoriteList favoriteList1 = new FavoriteList();
        favoriteList1.setUserId(userId);

        // 初始化 goodList 为空列表，避免 NullPointerException
        List<Good> goodList = new ArrayList<>();
        favoriteList1.setGoodList(goodList);

        // 通过 goodId 获取商品信息
        for (Favorite favorite : favoriteList) {
            Integer goodId = favorite.getGoodId();
            Good good = goodMapper.selectById(goodId);
            goodList.add(good);
        }

        // 返回分页结果
        return Result.success(Map.of(
                "favorites", favoriteList1,
                "total", favoriteListPage.getTotal(),
                "currentPage", page,
                "pageSize", pageSize,
                "totalPages", favoriteListPage.getPages()
        ));
    }


//    判断商品是否被收藏
    @GetMapping("/isFavorite")
    public Result<Boolean> isFavorite(
            @RequestParam Integer userId,
            @RequestParam Integer goodId
    ) {
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setGoodId(goodId);
        Favorite favorite1 = favoriteMapper.selectOne(favorite);
        if (favorite1 != null) {
            return Result.success(true);
        } else {
            return Result.success(false);
        }
    }
}
